package io.kimmking.dubbo.demo.second.provider.service.nettycharroom;

import io.kimmking.common.redis.repository.RedisRepository;
import io.kimmking.common.zookeeper.zktemplate.ZookeeperTemplate;
import io.kimmking.dubbo.common.balance.unit.BalanceUnit;
import io.kimmking.dubbo.common.service.charroom.CharRoomSelectorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetAddress;
import java.util.List;

@Slf4j
@DubboService(version = "1.0.0")
public class CharRoomSelectorServiceImpl implements CharRoomSelectorService {

    @Value("${km.netty.client.lb.type:hash}")
    private String loadBalanceType;

    private final ZookeeperTemplate zookeeperTemplate;

    private final RedisRepository redisRepository;

    public CharRoomSelectorServiceImpl (final ZookeeperTemplate zookeeperTemplate,
                                        final RedisRepository redisRepository) {
        this.zookeeperTemplate = zookeeperTemplate;
        this.redisRepository = redisRepository;
    }

    private List<String> getNettyServersFromZK() {

        return zookeeperTemplate.getChildren("netty_servers");

    }

    /**
     * todo:
     * 1、先从Redis查询该UserName对应聊天室NettyServer的信息是否存在
     * 2、如果没查询到，则从ZK中按照loadBalanceType的方法获取一台，并将UserName和聊天室NettyServer的路由信息保存至Redis中
     * @return
     * @throws Exception
     */
    @Override
    public String selectorFromList() throws Exception {
        List<String> upstreams = getNettyServersFromZK();
        return BalanceUnit.selector(upstreams,
                loadBalanceType,
                InetAddress.getLocalHost().getHostAddress());
    }

}
